# from email.mime import image

from datetime import datetime
from flask import Flask, request, render_template, send_file, jsonify, Response
import simplejson as json
import os
# from test import get_audio_data
import whisper
import torch

# ['tiny.en', 'tiny', 'base.en', 'base', 'small.en', 'small', 'medium.en', 'medium', 'large-v1', 'large-v2', 'large-v3', 'large']
# 提前加载好模型
print("loading model start...")
model = whisper.load_model(name="small", download_root=os.path.join(os.path.dirname(__file__), "model"), device=torch.device('cpu'))

print("loading model endpoint...")
app = Flask(__name__)
from flask_cors import CORS

CORS(app, supports_credentials=True)


@app.route('/')  # 代表首页
def index():  # 视图函数
    return "hello"


@app.route("/encoder", methods=['POST'])
def encoder():
    try:
        mp3 = request.files.get("file")  # 获取音频文件
        mp3_path = os.path.join(os.path.dirname(__file__), "static", mp3.filename)
        # 如果没有后缀，帮忙加上.mp3结尾的后缀，文件名随机

        # 获取当前时间
        current_time = datetime.now()
        # 将当前时间格式化为字符串
        current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
        print(current_time_str)
        if not mp3.filename.endswith(".mp3"):
            # 随机字符串+当前时间
            mp3_path = mp3_path + current_time_str+".mp3"

        mp3.save(mp3_path)  # 首先
        # 将mp3 文件保存成 wav格式

        result = model.transcribe(mp3_path)
        text = result["text"]
        return Response(json.dumps({
            "code": 200,
            "data": text
        }), mimetype='application/json')


    except Exception as e:
        print(e)
        return {
            "status": 0,
            "error": f"后端报错:{e}"
        }


app.config['DEBUG'] = True

if __name__ == '__main__':
    # 0.0.0.0代表任何能代表这台机器的地址都可以访问
    app.run(host='0.0.0.0', port=5001)  # 运行程序
    # http://8.133.188.11:5000/
